package com.wind.cloud.common.exception;

import com.wind.cloud.common.constant.ErrorCodes;
import com.wind.cloud.common.util.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 全局异常处理
 *
 * @author wind.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Object exceptionHandler(Throwable throwable, HttpServletRequest request, HttpServletResponse response) {
        if (throwable instanceof BindException) {
            log.info(throwable.toString());
            BindException bindException = (BindException) throwable;
            List<ObjectError> errors = bindException.getBindingResult().getAllErrors();
            if (errors != null && !errors.isEmpty()) {
                return ApiResult.error(ErrorCodes.VALIDATE_ERROR, errors.get(0).getDefaultMessage());
            }
        } else if (throwable instanceof IBusinessException) {
            log.warn(throwable.toString());
            IBusinessException businessException = (IBusinessException) throwable;
            return ApiResult.error(businessException.getCode(), businessException.getMessage());
        }
        log.error(throwable.getMessage(), throwable);
        return ApiResult.error(ErrorCodes.SYSTEM_ERROR, "SYSTEM BUSY!!!");
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd"), true));

        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"), true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy/MM/dd"), true));

    }
}
